package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author Pan Rundong
 * @Date 2023-02-02 10:12
 * @Desc 订单Service实现类
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 查看历史订单
     * @Author: Pan Rundong
     * @Date: 2023-02-06 9:23
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param page
     * @param pageSize
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.itheima.reggie.dto.OrdersDto>
     */
    @Override
    public Page<OrdersDto> getPage(int page, int pageSize) {
        //创建分页对象
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> dtoPage = new Page<>();

        //创建条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //根据Id查询
//        queryWrapper.eq(Orders::getStatus, 4);
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        this.page(ordersPage, queryWrapper);

        copyPage(ordersPage, dtoPage);
        return dtoPage;
    }

    /**
     * 修改订单状态
     * @Author: Pan Rundong
     * @Date: 2023-02-06 9:43
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param ordersDto
     * @return void
     */
    @Override
    public void updateStatus(OrdersDto ordersDto) {
        //查orders
        Orders orders = this.getById(ordersDto.getId());
        //更新状态
        orders.setStatus(ordersDto.getStatus());
        this.updateById(orders);
    }

    /**
     * 订单查询
     * @Author: Pan Rundong
     * @Date: 2023-02-05 21:38
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param page
     * @param pageSize
     * @param id
     * @param beginTime
     * @param endTime
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.itheima.reggie.dto.OrdersDto>
     */
    @Override
    public Page<OrdersDto> getPage(int page, int pageSize, Long id, LocalDateTime beginTime, LocalDateTime endTime) {
        //创建分页对象
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> dtoPage = new Page<>();

        //创建条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //根据Id查询
        queryWrapper.eq(id != null, Orders::getId, id);
        queryWrapper.between(beginTime != null && endTime != null,
                Orders::getOrderTime, beginTime, endTime);
        this.page(ordersPage, queryWrapper);

        copyPage(ordersPage, dtoPage);
        return dtoPage;
    }

    /**
     * 将orderDetail信息放入orderDto
     * @Author: Pan Rundong
     * @Date: 2023-02-06 9:22
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param ordersPage
     * @param dtoPage
     * @return void
     */
    private void copyPage(Page<Orders> ordersPage, Page<OrdersDto> dtoPage) {
        //拷贝
        BeanUtils.copyProperties(ordersPage, dtoPage, "records");

        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> list = records.stream().map((item) -> {
            //复制对应信息
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);

            //存订单详细信息OrderDetail
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper1);
            //储存
            ordersDto.setOrderDetails(orderDetailList);

            //存用户
            ordersDto.setUserName(item.getUserName());

            //查地址
            AddressBook addressBook = addressBookService.getById(item.getAddressBookId());
            ordersDto.setPhone(addressBook.getPhone());
            ordersDto.setConsignee(addressBook.getConsignee());
            ordersDto.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                    + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                    + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                    + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
            return ordersDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
    }

    /**
     * 用户下单
     * @param orders
     * @return void
     * @Author: Pan Rundong
     * @Date: 2023-02-02 10:37
     * @Greet2u: （O｀ 3′O）~~♡
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Orders submit(Orders orders) {
        //获得当前用户Id
        Long userId = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new CustomException("需要用户下单");
        }

        //查用户信息
        User user = userService.getById(userId);

        //查地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw new CustomException("地址信息不能为空");
        }

        //获得订单号
        long orderId = IdWorker.getId();
        AtomicInteger amount = new AtomicInteger();
        //可用LongAddr

        //设置OrderDetail
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            //拷贝
            BeanUtils.copyProperties(item,orderDetail);
            //设置orderId
            orderDetail.setOrderId(orderId);
            //计算金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //设置Orders
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(1);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据
        this.save(orders);

        //向订单明细表插入数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.remove(queryWrapper);
        return orders;
    }
}
